import api, { ApiResponse } from './api'
import { ExportFormat, ExportType, DocData, ExportSession, ExportOptions } from '@/lib/export-types'

// 导出服务类
export class ExportService {
  // 获取单文档内容
  static async getDocById(docId: string): Promise<DocData> {
    const response: ApiResponse = await api({
      url: '/doc/getDocByDocId',
      method: 'post',
      data: { docId }
    })

    if (response.success && response.data) {
      return {
        docTitle: response.data.docTitle,
        docContent: response.data.docContent,
        createTime: response.data.createTime
      }
    }
    throw new Error('获取文档失败')
  }

  // 获取目录及子目录所有文档
  static async getDirectoryDocs(teamId: string, projectId: string, directoryId: string): Promise<DocData[]> {
    const response: ApiResponse = await api({
      url: '/doc/listAllChildDirectoryDoc',
      method: 'post',
      data: { teamId, projectId, directoryId }
    })

    if (response.success && response.data) {
      return response.data
    }
    throw new Error('获取目录文档失败')
  }

  // 获取当前目录文档（不含子目录）
  static async getCurrentDirectoryDocs(teamId: string, projectId: string, directoryId: string): Promise<DocData[]> {
    const response: ApiResponse = await api({
      url: '/doc/listChildDirectoryDoc',
      method: 'post',
      data: { teamId, projectId, directoryId }
    })

    if (response.success && response.data) {
      return response.data
    }
    throw new Error('获取当前目录文档失败')
  }

  // 获取整个项目文档
  static async getProjectDocs(teamId: string, projectId: string): Promise<DocData[]> {
    const response: ApiResponse = await api({
      url: '/doc/listAllProjectDoc',
      method: 'post',
      data: { teamId, projectId }
    })

    if (response.success && response.data) {
      return response.data
    }
    throw new Error('获取项目文档失败')
  }

  // 生成文件名
  static generateFileName(exportType: ExportType, format: ExportFormat, projectName: string, directoryName?: string, docTitle?: string, isMerged: boolean = false): string {
    const extension = this.getFileExtension(format)
    console.log('generateFileName 被调用:', { exportType, format, extension, projectName, directoryName, docTitle, isMerged })
    
    let filename = ''
    switch (exportType) {
      case ExportType.SINGLE:
        if (isMerged) {
          filename = `${projectName}-多选文档-合并.${extension}`
        } else {
          filename = `${docTitle || '文档'}.${extension}`
        }
        break
      case ExportType.DIRECTORY:
      case ExportType.CURRENT_DIRECTORY:
        if (isMerged) {
          filename = `${projectName}-${directoryName || '目录'}-合并文档.${extension}`
        } else {
          filename = `${projectName}-${directoryName || '目录'}.${extension}`
        }
        break
      case ExportType.PROJECT:
        if (isMerged) {
          filename = `${projectName}-合并文档.${extension}`
        } else {
          filename = `${projectName}.${extension}`
        }
        break
      default:
        filename = `导出文档.${extension}`
    }
    
    console.log('生成的文件名:', filename)
    return filename
  }

  // 获取文件扩展名
  static getFileExtension(format: ExportFormat): string {
    switch (format) {
      case ExportFormat.MARKDOWN:
        return 'md'
      case ExportFormat.HTML:
        return 'html'
      case ExportFormat.PDF:
        return 'pdf'
      default:
        return 'md'
    }
  }

  // 检查文件大小
  static checkFileSize(content: string): boolean {
    const sizeInBytes = new Blob([content]).size
    const sizeInMB = sizeInBytes / (1024 * 1024)
    return sizeInMB <= 50 // 50MB限制
  }

  // 下载文件
  static downloadFile(content: string, filename: string, mimeType: string): void {
    console.log('ExportService.downloadFile 被调用:', { filename, mimeType, contentLength: content.length })
    
    // 确保文件名包含正确的扩展名
    const extension = this.getFileExtensionFromMimeType(mimeType)
    if (extension && !filename.endsWith(`.${extension}`)) {
      filename = `${filename}.${extension}`
      console.log('修正后的文件名:', filename)
    }
    
    const blob = new Blob([content], { type: mimeType })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    console.log('文件下载完成:', filename)
  }

  // 从MIME类型获取文件扩展名
  private static getFileExtensionFromMimeType(mimeType: string): string {
    switch (mimeType) {
      case 'text/markdown':
        return 'md'
      case 'text/html':
        return 'html'
      case 'application/pdf':
        return 'pdf'
      default:
        return ''
    }
  }

  // 获取MIME类型
  static getMimeType(format: ExportFormat): string {
    switch (format) {
      case ExportFormat.MARKDOWN:
        return 'text/markdown'
      case ExportFormat.HTML:
        return 'text/html'
      case ExportFormat.PDF:
        return 'application/pdf'
      default:
        return 'text/plain'
    }
  }
} 